package com.dfbz.controller;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp){
        String uri = req.getRequestURI();
        String s = uri.substring(uri.lastIndexOf("/") + 1);
        Class<? extends BaseServlet> aClass = this.getClass();
        Method method;
        try {
            method = aClass.getDeclaredMethod(s, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(aClass.newInstance(),req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected Map<String,String> getParam(HttpServletRequest req){
        HashMap<String, String> hashMap = new HashMap<>();
        Map<String, String[]> map = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = map.entrySet();
        for (Map.Entry<String,String[]> enp:entries) {
            String[] value = enp.getValue();
            if (value.length>1){
                hashMap.put(enp.getKey(),enp.getValue().toString());
            }else {
                hashMap.put(enp.getKey(),enp.getValue()[0]);
            }
        }
        return hashMap;
    }


}
